<template>
    <div>
        <div class="flex align-center justify-center gap-10 mar-t-30">
            <span>{{ label }}</span>
            <div class="input flex align-center justify-between pad-10 bg-f2f3f5 border-rad-5 w-80">
                <input
                    v-if="type === 'text'"
                    v-model="content"
                    class="input-init"
                    :placeholder="placeholder"
                    :maxlength="maxlength"
                    @input="handleInput"
                />

                <textarea
                    v-else
                    v-model="content"
                    :rows="rows"
                    class="input-init flex-1"
                    :placeholder="placeholder"
                    :maxlength="maxlength"
                    @input="handleInput"
                />
                <span class="color-8a919f">{{ count }} / {{ maxlength }}</span>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: {
            // 类型
            type: {
                type: String,
                default: 'text'
            },

            // 标签
            label: {
                type: String,
                default: ''
            },

            // 输入框值
            value: {
                type: String | Number,
                default: ''
            },

            // 输入框占位符
            placeholder: {
                type: String,
                default: ''
            },

            // 输入最大字数
            maxlength: {
                type: Number,
                default: 50
            },

            // 行数
            rows: {
                type: Number,
                default: 4
            }
        },

        watch: {
            // 监听父组件传值
            value(val) {
                this.content = val

                if (val) {
                    this.count = val.length
                }
            }
        },

        data() {
            return {
                count: 0, // 输入字数
                content: '', // 输入框内容
            }
        },

        mounted() {
        },

        methods: {
            handleInput(e) {
                this.count = e.target.value.length
                if(this.count > this.maxlength) {
                    this.content = e.target.value.slice(0, this.maxlength)
                } else {
                    this.content = e.target.value
                }
                this.$emit('input', e.target.value)
            }
        }
    }
</script>

<style scoped>
    input::placeholder {
        color: #BABEC6;
    }

    textarea {
        resize: none;
    }

    textarea::placeholder {
        color: #BABEC6;
    }

    .input:focus,
    .textarea:focus {
        background-color: #fff;
    }

    .input:focus-within,
    .textarea:focus-within {
        border: 1px solid #1e80ff;
        background-color: #fff;
    }
</style>